package ru.urfc.portal.ui.client.renderers;

import java.util.ArrayList;
import java.util.List;

import ru.urfc.portal.ui.client.Utils;
import ru.urfc.portal.ui.client.descriptor.CompositeGridField;
import ru.urfc.portal.ui.client.descriptor.GridField;
import ru.urfc.portal.ui.client.widgets.MegaGrid;

import com.extjs.gxt.ui.client.data.ModelData;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.Element;

public class UrlRenderer extends BaseRenderer {

	static private class GridFieldWithMarker {
		public GridField gridField;
		public String marker;

		public GridFieldWithMarker(GridField gridField, String marker) {
			this.gridField = gridField;
			this.marker = marker;
		}
	}
	
	private GridField idField;
	private String urlTemplate;
	private AnchorElement anchorTemplate;
	private Element textTemplate;
	private CompositeRenderer compositeRenderer;
	private List<GridFieldWithMarker> additionalFields = new ArrayList<GridFieldWithMarker>();

	public UrlRenderer(GridField textField, GridField idField,
			String urlTemplate, AnchorElement anchorTemplate, Element textTemplate) {
		super(textField);
		this.idField = idField;
		this.urlTemplate = urlTemplate;
		this.anchorTemplate = anchorTemplate;
		this.textTemplate = textTemplate;
		if (field instanceof CompositeGridField) {
			compositeRenderer = field.getRenderer();
		}
	}
	
	@Override
	protected void init(MegaGrid grid) {
		anchorTemplate = grid.getAnchorTemplate();
		textTemplate = grid.getAnchorTemplate(); 
	}

	public UrlRenderer(GridField textField, GridField idField,
			String urlTemplate, AnchorElement anchorTemplate) {
		this(textField, idField, urlTemplate, anchorTemplate, anchorTemplate);
	}	

	@Override
	public Object renderCell(ModelData modelData) {
		renderElements(modelData);
		return anchorTemplate.getParentElement().getInnerHTML();
	}
	
	@Override
	public void renderElements(ModelData modelData) {
		String text = compositeRenderer == null? field.<String>getValue(modelData): compositeRenderer.render(modelData);
		String url = renderUrl(modelData);
		anchorTemplate.setHref(url);
		textTemplate.setInnerText(text);
	}

	String renderUrl(ModelData modelData) {
		String id = idField.getValue(modelData);
		if (id == null) {
			return "";
		}
		String url = urlTemplate.replace("{0}", id);
		for (GridFieldWithMarker field: additionalFields) {
			String fieldValue = field.gridField.getValue(modelData);
			url = url.replace(field.marker, fieldValue);
		}
		return url;
	}

	public void addField(GridField gridField, String marker) {
		additionalFields.add(new GridFieldWithMarker(gridField, marker));
	}

	public void patchUrlTemplate(String debugParamValue) {
		urlTemplate = Utils.patchHref(urlTemplate, debugParamValue);
	}
	
	@Override
	public void updateModel(ModelData modelData) {
	}
	
}